import { asyncRoutes, constantRoutes } from '@/router'
import axios from 'axios'
import mmUrl from '@/utils/utilUrl'
import { _reduceArr1, _treeData } from '@/utils/util'
import Layout from '@/layout'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

function returnChildren(params) {
  const result = []
  params.forEach(v => {
    result.push({
      path: v.url.replace('/', ''),
      component: () => import(`@/views/${v.url.replace('/', '')}/index`),
      name: v.url.replace('/', ''),
      meta: {
        title: v.permissionName
      }
    })
  })
  return result
}
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        axios.post(mmUrl.login.ants).then(res => {
          sessionStorage.setItem('menu', JSON.stringify(res.data.data))
          const arrList1 = _reduceArr1(res.data.data)
          const filterA = arrList1.filter(v => v.permissionType === 'menu')
          if (!filterA.length) return false
          const resultA = [arrList1[0], ...filterA]
          const menuArr = _treeData(resultA.slice())[0].children
          var arr = []
          menuArr.forEach(v => {
            if (!v.children) {
              arr.push({
                path: v.url,
                component: Layout,
                children: [
                  {
                    path: 'index',
                    component: () =>
                      import(`@/views/${v.url.replace('/', '')}/index`),
                    name: v.url.replace('/', ''),
                    meta: {
                      title: v.permissionName,
                      icon: v.icon,
                      noCache: true
                    }
                  }
                ]
              })
            } else {
              arr.push({
                path: v.url ? '' : v.children[0].url,
                component: Layout,
                redirect: `${v.url ? '' : v.children[0].url}${
                  v.url ? '' : v.children[0].url
                }`,
                name: v.url ? '' : v.children[0].url,
                meta: {
                  title: v.permissionName,
                  icon: v.icon,
                  roles: ['admin', 'editor']
                },
                children: returnChildren(v.children)
              })
            }
          })
          accessedRoutes = arr || []
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        })
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
